package com.wonders.bigdata.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Description: <br>
 *
 * @author: XB
 * @date: 2021/4/28 9:29
 */
public class BIOServer {
    public static void main(String[] args) {
        // 线程池机制
        // 思路
        // 1.创建一个线程池
        // 2.如果有客户端连接，就创建一个线程阈值通讯
        try {
            ExecutorService cachedThreadPool = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());

            // 创建ServerSocket
            ServerSocket serverSocket = new ServerSocket(6666);
            System.out.println("服务器启动了");
            while (true) {
                // 监听，等待客户端连接
                final Socket accept = serverSocket.accept();
                System.out.println("连接到一个客户端" + accept.getLocalSocketAddress().getClass().getName());

                // 就创建一个线程与之通讯
                cachedThreadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        // 重写run方法，可以与客户端通讯
                        handler(accept);
                    }
                });
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 编写一个handler方法和客户端通讯
    public static void handler(Socket socket) {
        byte[] bytes = new byte[1024];
        try {
            System.out.println("线程信息id = " + Thread.currentThread().getId() + " 名字 = "
                    + Thread.currentThread().getName());
            // 通过socket获取输入流
            InputStream inputStream = socket.getInputStream();

            // 循环获取客户端发送的数据
            while (true) {
                System.out.println("线程信息id = " + Thread.currentThread().getId() + " 名字 = "
                        + Thread.currentThread().getName());
                int read = inputStream.read(bytes);
                if (read != -1) {
                    // 输出客户端发送的数据
                    System.out.println(new String(bytes, 0, read));
                }else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
